<%@page import="java.util.ArrayList"%>
<%@page import="com.restfb.util.StringUtils"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.task.GeneralTaskLevel"%>
<%@page import="fi.foyt.cs.Settings"%>
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<%@page import="java.util.List"%>
<%@page import="org.apache.commons.lang3.math.NumberUtils"%>
<%@page import="fi.foyt.cs.controller.LocaleController"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.locale.LocaleElement"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.task.GeneralTaskLevelCategory"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.scene.SceneCategory"%>
<%@page import="fi.foyt.cs.controller.SceneController"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.task.GeneralTask"%>
<%@page import="fi.foyt.cs.controller.TaskController"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.task.TaskType" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <jsp:include page="../fragments/head.jsp"></jsp:include>
</head>
<body>
  <jsp:include page="../fragments/header.jsp"></jsp:include>
  
  <%
    TaskController taskController = new TaskController();
    SceneController sceneController = new SceneController();
    LocaleController localeController = new LocaleController();
       
    if ("POST".equals(request.getMethod())) {
      List<SceneCategory> categories = sceneController.listSceneCategories();
      for (SceneCategory sceneCategory : categories) {
        Integer taskLevelCount = NumberUtils.createInteger(request.getParameter("category." + sceneCategory.getId().getId() + ".taskLevelCount"));
        if (taskLevelCount != null) {
          for (int i = 0; i < taskLevelCount; i++) {
            String taskLevelIdParam = request.getParameter("category." + sceneCategory.getId().getId() + ".taskLevel." + i + ".id");
            Long taskLevelId = StringUtils.isBlank(taskLevelIdParam) ? null : NumberUtils.createLong(taskLevelIdParam);
            String oldTaskLevelIdParam = request.getParameter("category." + sceneCategory.getId().getId() + ".taskLevel." + i + ".oldId");
            Long oldTaskLevelId = StringUtils.isBlank(oldTaskLevelIdParam) ? null : NumberUtils.createLong(oldTaskLevelIdParam);
          
            if (taskLevelId != null && taskLevelId > 0) {
              if (oldTaskLevelId == null) {
                // New
                GeneralTaskLevel generalTaskLevel = taskController.findGeneralTaskLevelById(taskLevelId);
                taskController.createGeneralTaskLevelCategory(generalTaskLevel, sceneCategory);
              } else if (!taskLevelId.equals(oldTaskLevelId)) {
                // Update
                GeneralTaskLevel oldGeneralTaskLevel = taskController.findGeneralTaskLevelById(oldTaskLevelId);
                GeneralTaskLevelCategory oldGeneralTaskLevelCategory = taskController.findGeneralTaskLevelCategoryByGeneralTaskAndCategory(oldGeneralTaskLevel, sceneCategory);
                taskController.deleteGeneralTaskLevelCategory(oldGeneralTaskLevelCategory);

                GeneralTaskLevel generalTaskLevel = taskController.findGeneralTaskLevelById(taskLevelId);
                taskController.createGeneralTaskLevelCategory(generalTaskLevel, sceneCategory);
              }
            } else if (taskLevelId == null && oldTaskLevelId != null) {
              GeneralTaskLevel oldGeneralTaskLevel = taskController.findGeneralTaskLevelById(oldTaskLevelId);
              GeneralTaskLevelCategory oldGeneralTaskLevelCategory = taskController.findGeneralTaskLevelCategoryByGeneralTaskAndCategory(oldGeneralTaskLevel, sceneCategory);
              taskController.deleteGeneralTaskLevelCategory(oldGeneralTaskLevelCategory);
            }
          }
        }
      }
    } 
    
    String startParameter = request.getParameter("start");
    int step = 10;
    int firstResult = (startParameter != null) && (!"".equals(startParameter)) ? new Integer(startParameter) : 1;
               
    pageContext.setAttribute("rootCategories", sceneController.listSceneCategories(null, firstResult - 1, step));
    pageContext.setAttribute("generalTasks", taskController.listGeneralTasks());
    
    List<Integer> setStarts = new ArrayList<Integer>(); 
    Integer rootCategoryCount = sceneController.countSceneCategories(null);
    for (int i = 0; i < rootCategoryCount; i += step) {
      setStarts.add(i + 1);
    }
    
    pageContext.setAttribute("step", step);
    pageContext.setAttribute("setStarts", setStarts);
    pageContext.setAttribute("currentStart", firstResult);
    pageContext.setAttribute("rootCategoryCount", rootCategoryCount);
  %>
  
  <h1>
    Map Generic Tasks To Categories
  </h1>
  
  <div style="max-width: 800px; margin-top: 8px; margin-bottom: 16px;">
    <c:forEach var="start" items="${setStarts}">
      <c:choose>
        <c:when test="${(start + step) < rootCategoryCount}">
          <c:set var="last">${start + step - 1}</c:set>
        </c:when>
        <c:otherwise>
          <c:set var="last">${rootCategoryCount}</c:set>
        </c:otherwise>
      </c:choose>
      
      <c:choose>
        <c:when test="${start == currentStart}">
          <a href="?start=${start}" style="white-space: nowrap; width: 70px; display: inline-block; text-align: center; border: 1px solid #6C8C97; color: #fff; background: #8CACB7">
            ${start} - ${last}
          </a>
        </c:when>
        <c:otherwise>
          <a href="?start=${start}" style="white-space: nowrap; width: 70px; display: inline-block; text-align: center; padding: 1px; color: #000">
            ${start} - ${last}
          </a>
        </c:otherwise>
      </c:choose>
    </c:forEach>
  </div>
  
  <form method="POST">
    <table>
      <c:forEach items="${rootCategories}" var="rootCategory">
        <tr>
          <td>${rootCategory.name}</td>
          <td>
	        <%
	          pageContext.setAttribute("categoryGeneralTaskLevels", taskController.listSceneCategoryGeneralTaskLevels(((SceneCategory) pageContext.getAttribute("rootCategory"))));
	        %>
	        <table>
	          <tr>
		        <c:set var="taskLevelIndex" value="0"/>
		        <c:forEach items="${categoryGeneralTaskLevels}" var="categoryGeneralTaskLevel">   
	   	        <c:set var="taskLevelIndex" value="${taskLevelIndex + 1}"/>
				      <td>
				        <input type="hidden" name="category.${rootCategory.id.id}.taskLevel.${taskLevelIndex}.oldId" value="${categoryGeneralTaskLevel.id.id}"/>
			            
			            <select name="category.${rootCategory.id.id}.taskLevel.${taskLevelIndex}.id">
			              <option></option>
			              <c:forEach items="${generalTasks}" var="generalTask">
			                <% 
			                  GeneralTask generalTask = (GeneralTask) pageContext.getAttribute("generalTask");
			                  LocaleElement localeElement = localeController.findLocaleElementById(generalTask.getLocaleElementId());
			                  String name = localeController.getLocalizedText(localeElement, Settings.getDefaultLocale());
			                  pageContext.setAttribute("generalTaskName", name);
	                      pageContext.setAttribute("levels", taskController.listGeneralTaskLevels(generalTask));
			                %>
	                    <c:forEach items="${levels}" var="level">
	                      <c:choose>
	                        <c:when test="${level eq categoryGeneralTaskLevel}">
	                          <option value="${level.id.id}" selected="selected">${generalTaskName} / ${level.levelNumber}</option>
	                        </c:when>
	                        <c:otherwise>
	                          <option value="${level.id.id}">${generalTaskName} / ${level.levelNumber}</option>
	                         </c:otherwise>
	                      </c:choose>
	                    </c:forEach>
			                
			              </c:forEach>
			            </select>
			            
			          </td>
	   	          <c:set var="taskLevelIndex" value="${taskLevelIndex + 1}"/>
		        </c:forEach>   
	            <td>
	              <select name="category.${rootCategory.id.id}.taskLevel.${taskLevelIndex}.id">
	                <option value="-1"></option>
	                <c:forEach items="${generalTasks}" var="generalTask">
			              <% 
			                GeneralTask generalTask = (GeneralTask) pageContext.getAttribute("generalTask");
			                LocaleElement localeElement = localeController.findLocaleElementById(generalTask.getLocaleElementId());
			                String name = localeController.getLocalizedText(localeElement, Settings.getDefaultLocale());
			                pageContext.setAttribute("generalTaskName", name);
                      pageContext.setAttribute("levels", taskController.listGeneralTaskLevels(generalTask));
			              %>
                    <c:forEach items="${levels}" var="level">
                      <option value="${level.id.id}">${generalTaskName} / ${level.levelNumber}</option>
                    </c:forEach>    
	                </c:forEach>
	              </select>
	              <input type="hidden" name="category.${rootCategory.id.id}.taskLevelCount" value="${taskLevelIndex + 1}"/>
	            </td>     
              </tr>
            </table>
          </td>
        </tr>
        
        <%
          pageContext.setAttribute("subCategories", sceneController.listSceneCategories((SceneCategory) pageContext.getAttribute("rootCategory")));
        %>

	    <c:forEach items="${subCategories}" var="subCategory">
	      <tr>
	        <td>&nbsp;&nbsp;&nbsp;&nbsp;${subCategory.name}</td>
	        <td>
		      <%
		        pageContext.setAttribute("categoryGeneralTaskLevels", taskController.listSceneCategoryGeneralTaskLevels(((SceneCategory) pageContext.getAttribute("subCategory"))));
		      %>
		      <table>
		        <tr>
			      <c:set var="taskLevelIndex" value="0"/>
			      <c:forEach items="${categoryGeneralTaskLevels}" var="categoryGeneralTaskLevel">   
		   	        <c:set var="taskLevelIndex" value="${taskLevelIndex + 1}"/>
				      <td>
				        <input type="hidden" name="category.${subCategory.id.id}.taskLevel.${taskLevelIndex}.oldId" value="${categoryGeneralTaskLevel.id.id}"/>
			            
			            <select name="category.${subCategory.id.id}.taskLevel.${taskLevelIndex}.id">
			              <option></option>
			              <c:forEach items="${generalTasks}" var="generalTask">
	                    <% 
	                      GeneralTask generalTask = (GeneralTask) pageContext.getAttribute("generalTask");
	                      LocaleElement localeElement = localeController.findLocaleElementById(generalTask.getLocaleElementId());
	                      String name = localeController.getLocalizedText(localeElement, Settings.getDefaultLocale());
	                      pageContext.setAttribute("generalTaskName", name);
	                      pageContext.setAttribute("levels", taskController.listGeneralTaskLevels(generalTask));
	                    %>
			                <c:forEach items="${levels}" var="level">
                        <c:choose>
			                    <c:when test="${level eq categoryGeneralTaskLevel}">
	                          <option value="${level.id.id}" selected="selected">${generalTaskName} / ${level.levelNumber}</option>
                          </c:when>
                          <c:otherwise>
                            <option value="${level.id.id}">${generalTaskName} / ${level.levelNumber}</option>
                           </c:otherwise>
  		                  </c:choose>
                      </c:forEach>
			              </c:forEach>
			            </select>
			          </td>
		   	        <c:set var="taskLevelIndex" value="${taskLevelIndex + 1}"/>
			      </c:forEach>   
		
		          <td>
		            <select name="category.${subCategory.id.id}.taskLevel.${taskLevelIndex}.id">
		              <option value="-1"></option>
		              <c:forEach items="${generalTasks}" var="generalTask">
                    <% 
                      GeneralTask generalTask = (GeneralTask) pageContext.getAttribute("generalTask");
                      LocaleElement localeElement = localeController.findLocaleElementById(generalTask.getLocaleElementId());
                      String name = localeController.getLocalizedText(localeElement, Settings.getDefaultLocale());
                      pageContext.setAttribute("generalTaskName", name);
                      pageContext.setAttribute("levels", taskController.listGeneralTaskLevels(generalTask));
                    %>
                    <c:forEach items="${levels}" var="level">
                      <option value="${level.id.id}">${generalTaskName} / ${level.levelNumber}</option>
                    </c:forEach>                    
		              </c:forEach>
		            </select>
		            <input type="hidden" name="category.${subCategory.id.id}.taskLevelCount" value="${taskLevelIndex + 1}"/>
		          </td>     
	            </tr>
	          </table>
	        </td>
	      </tr>
	    </c:forEach>      
      </c:forEach>
      
    </table>
    
    <input type="submit" value="Save"/>
  </form>
  
  <jsp:include page="../fragments/footer.jsp"></jsp:include>
</body>
</html>